package net.hzlj.platform.enterprise.utils.log;

import android.text.TextUtils;

import net.hzlj.platform.enterprise.utils.DateUtils;
import net.hzlj.platform.enterprise.utils.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: LogFile
 * @Description: 日志文件管理
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-23 11:10:52
 */
public class LogFile {

    public LogFile() {
    }

    public static void writeLogAppend(String tag, String msg) {
        //Log.setLogFilePath(Log.LOG_ROOT_FILE.getAbsolutePath() + "/Log-" + DateUtils.convertDateLongToString(System.currentTimeMillis(),"yyyyMMdd.txt"));
        if (Log.LOG_ROOT_FILE == null){
            return;
        }
        File file = new File(Log.LOG_ROOT_FILE,"/Log-" + DateUtils.convertDateLongToString(System.currentTimeMillis(),"yyyyMMdd") + ".txt");
        if (!file.exists()) {
            /*String randomFile = Log.FILE_PATH.substring(0, Log.FILE_PATH.lastIndexOf("/"));
            String[] filePaths = randomFile.split(File.separator);
            String cacheFilePath = File.separator;
            if (filePaths != null && filePaths.length > 0){
                for (int i = 0; i < filePaths.length; i++) {
                    cacheFilePath +=  filePaths[i];
                    File childFile = new File(cacheFilePath);
                    if (!childFile.exists()){
                        try {
                            childFile.mkdir();
                        }catch (Exception e){e.printStackTrace();}
                    }
                }
            }*/
            try {
                file.createNewFile();
                Log.FILE_PATH = file.getAbsolutePath();
            } catch (IOException var8) {
                var8.printStackTrace();
            }
        }
        if (TextUtils.isEmpty(Log.FILE_PATH)){
            return;
        }
        try {
            RandomAccessFile randomFile1 = new RandomAccessFile(Log.FILE_PATH, "rw");
            long e1 = randomFile1.length();
            if (e1 > (long) Log.FILE_MAX_LENGTH) {
                randomFile1.setLength(0L);
                e1 = 0L;
            }

            randomFile1.seek(e1);
            randomFile1.write(String.format("\n%s %s %s", getCurTime(), tag, msg).getBytes("gb2312"));
            randomFile1.close();
        } catch (FileNotFoundException var6) {
            var6.printStackTrace();
        } catch (IOException var7) {
            var7.printStackTrace();
        }

    }

    private static String getCurTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
        Date date = new Date(System.currentTimeMillis());
        return format.format(date);
    }
}
